package com.dyava.commons.lang;

/**
 * 字节工具
 */
public class ByteUtils {

	/**
	 * 数组转十六进制字符串
	 * 
	 * @param src
	 * @param toUpperCase
	 * @return
	 */
	public static String bytesToHexString(byte[] src, int offset, int len, boolean toUpperCase) {
		len = (len > src.length)? src.length : len;
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = offset; i < (offset + len); i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		if (toUpperCase) {
			return stringBuilder.toString().toUpperCase();
		} else {
			return stringBuilder.toString();
		}
	}

	public static String bytesToHexString(byte[] src, boolean toUpperCase) {
		return bytesToHexString(src,0,src.length,toUpperCase);
	}

	/**
	 * 十六进制字符串转数组
	 * 
	 * @param hexString
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexString.charAt(pos)) << 4 | charToByte(hexString.charAt(pos + 1)));
		}
		return d;
	}

	/**
	 * Convert char to byte
	 * 
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}
